package www.ym.com.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import www.ym.com.common.BaseContext;
import www.ym.com.common.CustomException;
import www.ym.com.common.R;
import www.ym.com.dto.OrdersDto;
import www.ym.com.entity.*;
import www.ym.com.mapper.OrdersMapper;
import www.ym.com.service.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService ordersDetailService;


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private AccountLogService accountLogService;

    @Autowired
    private OrdersMapper ordersMapper;


    @Transactional
    @Override

    /**
     * 购物车提交至订单
     */
    public void submit(OrdersDto ordersDto) {

        ordersDto.setStatus("0");
        ordersDto.setPayMethod(0);
        ordersDto.setOrderTime(LocalDateTime.now());
        this.save(ordersDto);

        log.info("orderId" + ordersDto.getId());

        List<OrderDetail> orderDetails = ordersDto.getOrderDetails();
        orderDetails = orderDetails.stream().map((item) -> {
            item.setOrderId(ordersDto.getId());
            return item;
        }).collect(Collectors.toList());
        ordersDetailService.saveBatch(orderDetails);

        //清空购物车
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, ordersDto.getUserId());
        shoppingCartService.remove(wrapper);
    }

    //修改订单状态
    @Override
    public String updateOrder(Orders order) {

        log.info("订单参数"+order);

        Orders orders = ordersService.getById(order.getId());
        User user = userService.getById(orders.getUserId());
        String msg = "";

        //支付
        //用户付款,冻结付款金额，
        if (orders.getStatus().equals("0") && order.getStatus().equals("1")) {
            log.info("是否进入" + "是");
            order.setCheckoutTime(LocalDateTime.now());
            ordersService.updateById(order);
            Account account = accountService.getById(order.getBankId());

            //判断银行卡金额是否大于付款金额
            if (orders.getAmount() <= account.getKyMenoy()) {
                log.info("是否进入"+account);
                AccountLog accountLog = new AccountLog();
                accountLog.setOrderId(orders.getId());
                accountLog.setBankId(order.getBankId());
                accountLog.setUserId(orders.getUserId());
                accountLog.setAccountName(account.getBankName());
                accountLog.setType("2");
                accountLog.setTradeAmt(orders.getAmount());
                accountLog.setOpName(user.getUsername());
                accountLog.setMessage("订单费用-冻结");
                accountLogService.save(accountLog);

                account.setKyMenoy(account.getKyMenoy() - orders.getAmount());
                account.setDjMenoy(account.getDjMenoy() + orders.getAmount());
                accountService.updateById(account);

                ordersService.updateById(order);
                msg = "支付成功";

            } else {
                throw new CustomException("该银行卡可用金额不足");
            }
        }

        //待派单或者派单中
        if(order.getStatus().equals("2")||order.getStatus().equals("3")){
            ordersService.updateById(order);
            msg="处理成功";
        }

        //完成订单
        if (order.getStatus().equals("4")) {
            Account account = accountService.getById(orders.getBankId());
            if (orders.getAmount() <= account.getDjMenoy()) {
                AccountLog accountLog = new AccountLog();
                accountLog.setOrderId(orders.getId());
                accountLog.setBankId(orders.getBankId());
                accountLog.setUserId(orders.getUserId());
                accountLog.setAccountName(account.getBankName());
                accountLog.setType("1");
                accountLog.setTradeAmt(orders.getAmount());
                accountLog.setOpName(user.getUsername());
                accountLog.setMessage("订单费用-减少");
                accountLogService.save(accountLog);

                account.setDjMenoy(account.getDjMenoy() - orders.getAmount());
                account.setTotalMenoy(account.getKyMenoy()-orders.getAmount());
                accountService.updateById(account);

                ordersService.updateById(order);
                msg = "订单完成";
            } else {
                throw new CustomException("冻结金额不足完成订单失败");
            }
        }

        //待支付取消订单
        if (order.getStatus().equals("5") && orders.getStatus().equals("0")) {
            ordersService.updateById(order);
            msg = "取消订单成功";
        }
        //待接单取消订单
        if (order.getStatus().equals("5") && orders.getStatus().equals("1")) {
            Account account = accountService.getById(orders.getBankId());
            if (orders.getAmount() <= account.getDjMenoy()) {
                AccountLog accountLog = new AccountLog();
                accountLog.setOrderId(orders.getId());
                accountLog.setBankId(orders.getBankId());
                accountLog.setUserId(orders.getUserId());
                accountLog.setAccountName(account.getBankName());
                accountLog.setType("3");
                accountLog.setTradeAmt(orders.getAmount());
                accountLog.setOpName(user.getUsername());
                accountLog.setMessage("取消订单-解冻");
                accountLogService.save(accountLog);

                account.setKyMenoy(account.getKyMenoy() + orders.getAmount());
                account.setDjMenoy(account.getDjMenoy() - orders.getAmount());
                accountService.updateById(account);
                log.info("account"+account);

                ordersService.updateById(order);
                msg = "取消订单成功";
            } else {
                throw new CustomException("冻结金额不足，取消订单失败");
            }
        }

        return msg;
    }

    @Override
    public Page<Orders> Pagelist(JSONObject jsonObject) {
        //当前页数
        Long pageNum = Long.valueOf(String.valueOf(jsonObject.get("pageNum")));
        //每页显示数
        Long pageSize = Long.valueOf(String.valueOf(jsonObject.get("pageSize")));
        //状态
        Long userId = Long.valueOf(String.valueOf(jsonObject.get("userId")));
        //状态
        String status = (String.valueOf(jsonObject.get("status")));
//        log.info("当前页为" + pageNum);
//        log.info("每页显示数" + pageSize);
//        log.info("订单状态" + status);

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Orders::getUserId, userId)
                .eq(!status.equals(""), Orders::getStatus, status);

//                .notIn(Role::getRoleName, "超级管理员", "管理员");
        wrapper.orderByDesc(Orders::getOrderTime);

        //进行分页查询-可跟条件
        Page<Orders> urf = ordersMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        System.out.println("数据为：" + urf.getRecords());
        System.out.println("总数为：" + urf.getTotal() + ",总页数为：" + urf.getPages());
        System.out.println("当前页为：" + urf.getCurrent() + ",每页限制：" + urf.getSize());
        return urf;
    }


//    @Transactional
//    @Override
//    public void submit(OrdersDto ordersDto) {

//        //获得当前用户id
//        Long userId = BaseContext.getCurrentId();
//
//        //查询当前用户的购物车数据
//        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(ShoppingCart::getUserId,userId);
//        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
//
//        if(shoppingCarts == null || shoppingCarts.size() == 0){
//            throw new CustomException("购物车为空，不能下单");
//        }
//
//        //查询用户数据
//        User user = userService.getById(userId);
//
//        //查询地址数据
//        Long addressBookId = orders.getAddressBookId();
//        AddressBook addressBook = addressBookService.getById(addressBookId);
//        if(addressBook == null){
//            throw new CustomException("用户地址信息有误，不能下单");
//        }
//
//        long orderId = IdWorker.getId();//订单号
//
//        AtomicInteger amount = new AtomicInteger(0);
//
//        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
//            OrderDetail orderDetail = new OrderDetail();
//            orderDetail.setOrderId(orderId);
//            orderDetail.setNumber(item.getNumber());
//            orderDetail.setDishFlavor(item.getDishFlavor());
//            orderDetail.setDishId(item.getDishId());
//            orderDetail.setSetmealId(item.getSetmealId());
//            orderDetail.setName(item.getName());
//            orderDetail.setImage(item.getImage());
//            orderDetail.setAmount(item.getAmount());
//            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
//            return orderDetail;
//        }).collect(Collectors.toList());
//
//
//
//        //一条订单中含有几个商品
////        List<String> goods = shoppingCarts.stream().map((item) -> {
////            return item.getName();
////        }).collect(Collectors.toList());
////        log.info("商品货物为：{}",goods);
//
//        orders.setId(orderId);
//        orders.setOrderTime(LocalDateTime.now());
//        orders.setCheckoutTime(LocalDateTime.now());
//        orders.setStatus(2);
//        orders.setAmount(new BigDecimal(amount.get()));//总金额
//        orders.setUserId(userId);
//        orders.setNumber(String.valueOf(orderId));
//        orders.setUserName(user.getUsername());
//        orders.setConsignee(addressBook.getConsignee());
//        orders.setPhone(addressBook.getPhone());
////        orders.setOrderDetails(goods);
//        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
//                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
//                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
//                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
//
//
//        //向订单表插入数据，一条数据
//        ordersService.save(orders);
//
//        //向订单明细表插入数据，多条数据
//        ordersDetailService.saveBatch(orderDetails);
//
//        //清空购物车数据
//        shoppingCartService.remove(wrapper);
//    }
}

